<template>
  <div class="app-container calendar-list-container">
    <!-- 搜索工具栏 -->
    <section>
      <so-tool-bar :toolData="toolData" :query="listQuery" @search="search"/>
    </section>
    <!-- 其他操作 -->
    <section class="filter-container">
      <el-row>
        <el-col :span="6">
          <el-button class="filter-item" type="primary" size="small" @click="upAndownPro(1)">上架</el-button>
          <el-button class="filter-item" type="primary" size="small" @click="upAndownPro(0)">下架</el-button>
          <el-button class="filter-item" type="primary" size="small" @click="topStatus(1)">置顶</el-button>
          <el-button class="filter-item" type="primary" size="small" @click="topStatus(0)">取消置顶</el-button>
        </el-col>
        <el-col :span="6" style="padding-top: 5px;">
          &nbsp;&nbsp;<span class="el-green">已结束&nbsp;<em>{{listQuery.total || 0 }}</em>&nbsp;个</span>
          &nbsp;&nbsp;<span class="el-green">预约中&nbsp;<em>{{inhand_count || 0 }}</em>&nbsp;个</span>
          &nbsp;&nbsp;<span class="el-green">进行中&nbsp;<em>{{inhand_count || 0 }}</em>&nbsp;个</span>
        </el-col>
        <el-col :span="12">
          <section style="float: right">
            <el-button class="filter-item" type="danger" size="small" @click="delRows">批量删除</el-button>
            <el-button class="filter-item" type="primary" size="small" @click="openForm('add')">发布活动</el-button>
          </section>
        </el-col>
      </el-row>
    </section>
    <!-- 表格 -->
    <el-table :data="tableList" v-loading="loading" element-loading-text="正在查询中。。。" stripe highlight-current-row @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column align="center" width="90">
        <template slot-scope="scope">
          <el-tag size="mini" :type="t_active[scope.row.active_status - 1].type">{{t_active[scope.row.active_status - 1].name}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" width="30">
        <template slot-scope="scope">
          <i class="iconfont ali-zhiding" v-show="scope.row.top_status == 1"></i>
        </template>
      </el-table-column>
      <el-table-column align="center" label="活动主题" prop="active_title" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" label="活动时间" width="150px" show-overflow-tooltip>
        <template slot-scope="scope">
          <span>{{scope.row.active_start_time}}</span><br/>
          <span>{{scope.row.active_end_time}}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="地点" prop="active_address" show-overflow-tooltip>
      </el-table-column>
      <el-table-column align="center" label="开始报名时间" width="150px" prop="signup_start_time">
      </el-table-column>
      <el-table-column align="center" label="报名人数">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="alreadySign(scope.row)">{{scope.row.readyapply_nums}} / {{scope.row.allow_num}}</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="浏览量" prop="browse_nums">
      </el-table-column>
      <el-table-column align="center" label="报名范围" width="100px" show-overflow-tooltip>
        <template slot-scope="scope">
          <i v-for="item in scope.row.activeRanges" :key="item.id">
            <span>{{item.organization_name}}</span>/
          </i>
        </template>
      </el-table-column>
      <el-table-column align="center" label="发布时间" prop="create_time">
      </el-table-column>
      <el-table-column align="center" label="状态">
        <template slot-scope="scope">
          <el-tag size="mini" type="success">{{t_status[scope.row.close_status]}}</el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="列表链接">
        <template slot-scope="scope">
          <el-button
            v-clipboard:copy="'https://cloud.anyolife.com/ActivityHome'"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            type="text"
          >复制链接</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="详情链接">
        <template slot-scope="scope">
          <el-button
            v-clipboard:copy="'https://cloud.anyolife.com/ActivityDetail' + '?id=' + scope.row.id
            + '&status=' + scope.row.active_status + '&name=' + 'home'"
            v-clipboard:success="onCopy"
            v-clipboard:error="onError"
            type="text"
          >复制链接</el-button>
        </template>
      </el-table-column>
      <el-table-column align="center" label="操作" width="150px">
        <template slot-scope="scope">
          <el-button type="text" size="mini" @click="openForm('edit', scope.row)">编辑</el-button>
          <el-button type="text" size="mini" @click="delRow(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <section>
      <so-pagination :query="listQuery" @initList="initList"/>
    </section>
    <!-- 发布活动 -->
    <section>
      <el-dialog :visible.sync="dialog.isShow" :show-close="false" :fullscreen="fullscreen" :before-close="beforeClose" :close-on-click-modal="false">
        <el-row slot="title">
          <el-col :span="10" style="padding-top: 5px">
            <span style="font-size: 18px;">{{dialog.title}}</span>
          </el-col>
          <el-col :span="2" :offset="11">
            <el-button type="text" v-if="!fullscreen" icon="iconfont ali-quanping" @click="fullscreen = true" style="float: right"></el-button>
            <el-button type="text" v-else icon="iconfont ali-zuixiaohua" @click="fullscreen = false" style="float: right"></el-button>
          </el-col>
          <el-col :span="1">
            <el-button type="text" icon="iconfont ali-guanbi" @click="dialog.isShow = false" style="float: right"></el-button>
          </el-col>
        </el-row>
        <el-form :model="form" ref="createActive" label-width="90px">
          <el-form-item label="活动主题" prop="active_title" :rules="filter_rules({required:true})">
            <el-input clearable style="width: 300px;" placeholder="请输入活动主题" v-model.trim="form.active_title">
            </el-input>
          </el-form-item>
          <el-form-item label="活动时间" prop="form_active_time" :rules="filter_rules({required:true})">
            <el-date-picker v-model="form.form_active_time" type="daterange" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="活动封面" prop="file_path" :rules="filter_rules({type: 'upload'})">
            <img v-if="form.file_path" :src="form.file_path" class="avatar" @click="sizeSet">
            <i v-else class="el-icon-plus avatar-uploader-icon" @click="sizeSet"></i>
          </el-form-item>
          <el-form-item label="报名时间" prop="form_signup_time" :rules="filter_rules({required:true})">
            <el-date-picker v-model="form.form_signup_time" type="daterange" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期">
            </el-date-picker>
          </el-form-item>
          <el-form-item label="活动地点" prop="active_address" :rules="filter_rules({required:true})">
            <el-input clearable style="width: 300px;" placeholder="请输入活动地点" v-model.trim="form.active_address">
            </el-input>
          </el-form-item>
          <el-form-item label="报名人数" prop="allow_num" :rules="filter_rules({required:true, type: 'integer'})">
            <el-input clearable style="width: 300px;" placeholder="请输入可报名人数" v-model.number="form.allow_num">
            </el-input>
          </el-form-item>
          <el-form-item label="部门范围">
            <el-tag v-for="dept in form.depts" :key="dept.id" style="margin-right:6px;">{{dept.label}}</el-tag>
            <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openDeptModal('dept')"></el-button>
          </el-form-item>
          <el-form-item label="小组范围">
            <el-tag v-for="group in form.groups" :key="group.id" style="margin-right:6px;">{{group.group_name}}</el-tag>
            <el-button size="mini" type="text" icon="iconfont ali-add" circle @click="openDeptModal('group')"></el-button>
          </el-form-item>
          <el-form-item label="定义字段">
            <fields ref="fieldTemp"></fields>
          </el-form-item>
          <!-- <so-wang-editor ref="editor" :content="form.active_content"/> -->
          <el-form-item label="活动内容">
            <UE @showUpload="showUpload" :defaultMsg.sync='defaultMsg' ref="ue"></UE>
          </el-form-item>
        </el-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialog.isShow = false">取 消</el-button>
          <el-button type="primary" @click="validate('createActive')">保 存</el-button>
        </span>
      </el-dialog>
    </section>
    <!-- 部门 和小组 组件 -->
    <section>
      <dept-transfer ref="deptInit" @closeTransfer="transfer.deptShow = false" @getDepts="getDepts" :isShow="transfer.deptShow"></dept-transfer>
      <group-transfer ref="groupInit" @closeTransfer="transfer.groupShow = false" @getGroups="getGroups" :isShow="transfer.groupShow"></group-transfer>
    </section>
    <section>
      <size-temp ref="size" :img.sync="form.file_path" title="图片设置"></size-temp>
    </section>
    <section>
      <UeUpload ref="vupload" @addUeditorImg="addUeditorImg" img="卐" title="添加图片"></UeUpload>
    </section>
  </div>
</template>

<script>
import { active_list, active_save, active_edit, active_updateCloseStatus, active_updateTopStatus, active_delete, active_deleteAll, active_findById } from "@/api/active";
import { listAddress } from "@/api/address";
import { searchTool } from "@/utils";
// import SoWangEditor from "@/components/SoWangEditor";
import UE from '@/components/Ueditor';
import deptTransfer from "@/views/activity/components/add_dept_transfer";
import groupTransfer from "@/views/activity/components/add_group_transfer";
import SoPagination from "@/components/SoPagination";
import SoToolBar from "@/components/SoToolBar";
import { status_opt, t_active, t_status, toolData } from "./activity";
import sizeTemp from '@/components/draggableSize'
import UeUpload from '@/components/UeUpload'
import fields from './fields'

export default {
  name: "activityManage",
  components: {
    deptTransfer,
    groupTransfer,
    SoPagination,
    SoToolBar,
    sizeTemp,
    fields,
    UeUpload,
    UE
  },
  data() {
    return {
      toolData: toolData, //工具栏初始化
      loading: false,
      tableList: [],
      multipleSelection: [],
      listQuery: { start: 0, limit: 10, total: 0, current: 1 },
      t_active: t_active,
      t_status: t_status,
      status_opt: status_opt,
      dialog: { isShow: false },
      fullscreen: false,
      transfer: { deptShow: false, groupShow: false },
      ossPublicUrl: localStorage.getItem("ossPublicUrl"),
      form: {file_path: ''},
      fromStatus: "", //判断是add 还是edit
      inhand_count: 0, //正在进行的数量
      defaultMsg: ''
    };
  },
  methods: {
    onCopy: function() {
      this.$message({
        type: "success",
        message: "复制成功"
      });
    },
    onError: function() {
      this.$message.error("复制失败");
    },
    showUpload(){
      this.$refs.vupload.open()
    },
    addUeditorImg(val){
      this.$refs.ue.addToContent(`<img src="${val}">`)
    },
    beforeClose(done){
      this.$refs.ue.clear();
      done()
    },
    sizeSet(){
      this.$refs.size.open()
    },
    alreadySign(e) {//跳转到查看已报名人员列表
      this.$router.push({path: "/activity/alreadySign", query: { id: e.id, a_num: e.readyapply_nums, h_num: e.allow_num }});
    },
    async saveObj() {
      try {
        const params = {...this.form, company_id: localStorage.getItem("companyId") - 0};
        this.loading = true;
        const { data } = this.fromStatus == "add" ? await active_save(params) : await active_edit(params);
        this.loading = false;
        if (data.status == 100) {
          this.$message.success(this.fromStatus == "add" ? "添加成功" : "编辑成功" );
          this.form = {file_path: ''}; //清空数据
          this.initList();
        }
      } catch (error) {
        console.log(error,'error')
      }
    },
    validate(e) {
      const _fields = this.$refs.fieldTemp.dynamicTags;
      this.form.activefields = JSON.stringify(_fields);
      // this.form.active_content = this.$refs.editor.getContent(); //富文本内容
      this.form.active_content = this.$refs.ue.getContent(); //富文本内容
      this.$refs[e].validate(valid => {
        if (valid) {
          this.form.active_start_time = this.form.form_active_time[0].indexOf("00:00:00") > 0 ? this.form.form_active_time[0] : this.form.form_active_time[0] + " 00:00:00";
          this.form.active_end_time = this.form.form_active_time[1].indexOf("23:59:59") > 0 ? this.form.form_active_time[1] : this.form.form_active_time[1] + " 23:59:59";
          this.form.signup_start_time = this.form.form_signup_time[0].indexOf("00:00:00") > 0 ? this.form.form_signup_time[0] : this.form.form_signup_time[0] + " 00:00:00";
          this.form.signup_end_time = this.form.form_signup_time[1].indexOf("23:59:59") > 0 ? this.form.form_signup_time[1] : this.form.form_signup_time[1] + " 23:59:59";
          this.form.close_status = 0; //默认不上架
          let depts = [], groups = [];
          if (this.form.depts && this.form.depts.length > 0) {
            depts = this.form.depts.map(item => {
              return { range_type: 1, organization_id: item.id };
            });
          }
          if (this.form.groups && this.form.groups.length > 0) {
            groups = this.form.groups.map(item => {
              return { range_type: 2, organization_id: item.id };
            });
          }
          depts.push(...groups);
          this.form.activeRanges = JSON.stringify(depts);
          this.saveObj();
          this.dialog.isShow = false;
        } else {
          return false;
        }
      });
    },
    beforeAvatarUpload(file) {
      let name = file.name.split(".");
      if (name[name.length - 1] === "jpg" || name[name.length - 1] === "jpeg" || name[name.length - 1] === "png" ) {
        return file;
      } else {
        this.$message.error("图片只能是 jpeg/png 格式!");
        return false;
      }
    },
    handleAvatarSuccess(res, file) {
      this.form.file_path = this.ossPublicUrl + "/" + res.data.file_path;
    },
    getGroups(e) {//获取小组
      if (e.length == 0) {
        this.$message.warning("至少要选择一个小组");
        return;
      }
      this.form.groups = e;
      this.transfer.groupShow = false;
    },
    getDepts(e) {//获取部门
      if (e.length == 0) {
        this.$message.warning("至少要选择一个部门");
        return;
      }
      this.form.depts = e;
      this.transfer.deptShow = false;
    },
    openDeptModal(e) {//打开穿梭框组件
      if (e == "dept") {
        this.transfer.deptShow = true;
      } else {
        this.transfer.groupShow = true;
      }
    },
    async delRows(){//批量删除
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择需要调整单元");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      try {
        const res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          const { data } = await active_deleteAll({array: ids});
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
        }
      } catch (error) {
        console.log(error, "error");
      }
    },
    async delRow(row) {//删除
      try {
        let res = await this.$confirm("确认删除吗？");
        if (res == "confirm") {
          this.loading = true;
          let { data } = await active_delete(row);
          if (data.status == 100) {
            this.$message.success("删除成功");
          }
          this.initList();
        }
      } catch (error) {}
    },
    async openForm(e, row) {//打开活动面板
      if (e == "add") {
        this.fromStatus = "add";
        this.form = {file_path: ''}; //清空数据
        this.$refs.deptInit.clear();
        this.$refs.groupInit.clear();
        this.dialog = {isShow: true, title: "发布活动" };
        this.defaultMsg = ''//清空富文本
        this.$nextTick(_ => {
          this.$refs.fieldTemp.dynamicTags = [];
          // this.$refs.editor.clear(); //清空富文本
          this.$refs.ue.setContent('<br/>'); //清空富文本
        });
      } else {
        const {data} = await active_findById({id: row.id});
        if(data.status != 100){
          this.$message.warning('数据获取异常')
          return;
        }
        this.fromStatus = "edit";
        this.dialog = {isShow: true, title: "编辑活动" };
        // this.form = data.data;
        const params = {
            form_active_time: [data.data.active_start_time, data.data.active_end_time],
            form_signup_time: [data.data.signup_start_time, data.data.signup_end_time]
        }
        // this.form.form_active_time = [this.form.active_start_time, this.form.active_end_time ];
        // this.form.form_signup_time = [this.form.signup_start_time, this.form.signup_end_time ];
        this.form = {...data.data, ...params}
        this.form.depts = [];
        this.form.groups = [];
        for (var i = 0; i < this.form.activeRanges.length; i++) {
          var element = this.form.activeRanges[i];
          if (element.range_type == 1) {
            this.form.depts.push({id: element.organization_id, label: element.organization_name });
          } else {
            this.form.groups.push({id: element.organization_id, group_name: element.organization_name });
          }
        }
        this.defaultMsg = this.form.active_content
        this.$nextTick(_ => {
          this.$refs.fieldTemp.dynamicTags = data.data.activefields
          this.$refs.ue.setContent(this.defaultMsg)
        });
      }
    },
    handleSelectionChange(e) {
      this.multipleSelection = e;
    },
    async upAndownPro(e) {//1 上架 0下架
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择需要调整单元");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      this.loading = true;
      let { data }  = await active_updateCloseStatus({ ids: ids, close_status: e });
      this.loading = false;
      if (data.status === 100) {
        await this.initList();
        this.$message.success(`${this.t_status[e]}成功`);
      }
    },
    async topStatus(e) {  //置顶为1,取消置顶为0
      if (this.multipleSelection.length == 0) {
        this.$message.warning("请先选择需要调整单元");
        return;
      }
      const ids = this.multipleSelection.map(item => item.id).join();
      this.loading = true;
      let { data }  = await active_updateTopStatus({ ids: ids, top_status: e });
      this.loading = false;
      if (data.status === 100) {
        this.$message.success('操作成功')
        await this.initList();
      }
    },
    search() {//搜索
      let keyWords = {key: "searchDate", names: ["active_start_time", "active_end_time"]};
      this.listQuery = searchTool(this.listQuery, keyWords);
      this.initList();
    },
    async initList() {
      this.loading = true;
      const query = {...this.listQuery, company_id: localStorage.getItem("companyId") - 0};
      const { data } = await active_list(query);
      this.loading = false;
      if (data.status == 100) {
        this.tableList = data.data.rows;
        this.listQuery.total = data.data.results;
        this.inhand_count = data.data.inhand_count;
      }
    }
  },
  created() {
    this.initList();
  }
};
</script>
<style lang="scss" scoped>
$border: 1px dashed #d9d9d9;
$picture-size: 120px;
$color: #606266;
span {
  font-size: 13px;
  color: $color;
}
.ali-zhiding{
  color: #009900;
  font-size: 20px;
}
.avatar-uploader {
  .el-upload {
    border: $border;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    &:hover {
      border-color: #409eff;
    }
  }
}
.avatar-uploader-icon {
  border: $border;
  font-size: 28px;
  color: #8c939d;
  width: $picture-size;
  height: $picture-size;
  line-height: $picture-size;
  text-align: center;
  border-radius: 5px;
  cursor: pointer;
}
.avatar {
  width: 60%;
  display: block;
  border-radius: 5px;
  cursor: pointer;
}
</style>
